﻿/* ============================================================================
(c) Copyright 2012 Hewlett-Packard Development Company, L.P.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge,publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
============================================================================ */
using System;
using System.Collections.Generic;
using System.Linq;
using HPCloud.Common;
using HPCloud.Objects.Domain;
using HPCloud.Objects.Utility;
using System.IO;
using System.Collections.Specialized;
using System.Net.Http;
using System.Diagnostics.Contracts;
using HPCloud.Objects.Domain.Storage;
using System.Xml.Linq;
using System.Xml.XPath;

namespace HPCloud.Objects.DataAccess.Storage
{
    public class ContainerRepository : BaseRepository, IContainerRepository
    {
        const string cDelimiter = "/";

        #region Ctors
//======================================================================================================================
/// <summary>
/// 
/// </summary>
/// <param name="settings"></param>
//======================================================================================================================
        public ContainerRepository(RepositoryContext context) : base(context)
        { }
        #endregion
        #region Methods
//============================================================================================================================
/// <summary>
/// 
/// </summary>
/// <param name="containerName"></param>
//============================================================================================================================

        //public void SetScope(string containerName, ContainerACL acl)
        //{
        //    NameValueCollection headers = new NameValueCollection();
        //    foreach (string username in acl.Users)
        //    {
        //        if (acl.Permission == ContainerPermissions.PublicRead) {
        //            headers.Add("X-Container-Read", username);
        //            this.InvokeEndpoint(HttpMethod.Put, this.Context.ServiceDescription.Url + "/" + containerName, null, headers);
        //        }
        //        else if (acl.Permission == ContainerPermissions.PublicWrite || acl.Permission == ContainerPermissions.PublicReadWrite)
        //        {
        //            headers.Add("X-Container-Write", username);
        //            this.InvokeEndpoint(HttpMethod.Put, this.Context.ServiceDescription.Url + "/" + containerName, null, headers);
        //        }
        //        else if (acl.Permission == ContainerPermissions.PublicReadWrite)
        //        {
        //            headers.Add("X-Container-Write", username);
        //            headers.Add("X-Container-Read", username);
        //            this.InvokeEndpoint(HttpMethod.Put, this.Context.ServiceDescription.Url + "/" + containerName, null, headers);
        //        }        
        //    }
        //}
        public void SetScope(string containerName, ContainerACL acl)
        {
            NameValueCollection headers = new NameValueCollection();
            foreach (string username in acl.Users)
            {
                if (acl.Permission == ContainerPermissions.PublicRead) {
                    headers.Add("X-Container-Read", username);
                    this.InvokeEndpoint(HttpMethod.Put, this.Context.ServiceDescription.Url + "/" + containerName, null, headers);
                }
                else if (acl.Permission == ContainerPermissions.PublicWrite || acl.Permission == ContainerPermissions.PublicReadWrite)
                {
                    headers.Add("X-Container-Write", username);
                    this.InvokeEndpoint(HttpMethod.Put, this.Context.ServiceDescription.Url + "/" + containerName, null, headers);
                }
                else if (acl.Permission == ContainerPermissions.PublicReadWrite)
                {
                    headers.Add("X-Container-Write", username);
                    headers.Add("X-Container-Read", username);
                    this.InvokeEndpoint(HttpMethod.Put, this.Context.ServiceDescription.Url + "/" + containerName, null, headers);
                }        
            }
        }

//============================================================================================================================
/// <summary>
/// 
/// </summary>
/// <param name="containerName"></param>
//============================================================================================================================
        public void SetScope(string containerName, ContainerScope scope)
        {
            NameValueCollection headers = new NameValueCollection();

            if (scope == ContainerScope.Public)
            {               
                headers.Add("X-Container-Read", ".r:*,.rlistings");
                this.InvokeEndpoint(HttpMethod.Put, this.Context.ServiceDescription.Url + "/" + containerName, null, headers);
            }
            else
            {                
                headers.Add("X-Container-Read", " ");
                this.InvokeEndpoint(HttpMethod.Put, this.Context.ServiceDescription.Url + "/" + containerName, null, headers);
            }
        }
//======================================================================================================================
/// <summary>
/// 
/// </summary>
/// <param name="name"></param>
/// <returns>Indicates if the operation worked or not.</returns>
//======================================================================================================================
        public bool DeleteContainer(string name)
        {
            StorageContainer storageContainer = new StorageContainer(name);
            return this.DeleteContainer(storageContainer);
        }
//======================================================================================================================
/// <summary>
/// 
/// </summary>
//======================================================================================================================
        public bool DeleteContainer(StorageContainer storageContainer)
        {
            // First, remove all of the Containers contents..

            try
            {
                StorageObjects storageObjects = this.InvokeEndpoint<StorageObjects>(HttpMethod.Get, this.Context.ServiceDescription.Url + "/" + storageContainer.Name, null);

                if (storageObjects != null && storageObjects.List.Count > 0)
                {
                    foreach (StorageObject storageObject in storageObjects.ToList())
                    {
                        this.InvokeEndpoint(HttpMethod.Delete, this.Context.ServiceDescription.Url + "/" + storageContainer.Name + "/" + storageObject.Key, null, null);
                    }
                }

                this.InvokeEndpoint(HttpMethod.Delete, this.Context.ServiceDescription.Url + "/" + storageContainer.Name, null, null);
            }
            catch (InvalidOperationException)
            { return true; }
            
            return true;
        }
////======================================================================================================================
///// <summary>
///// 
///// </summary>
///// <param name="path"></param>
///// <returns></returns>
////======================================================================================================================
        public List<KeyValuePair<string, string>> GetMetaData(string source)
        {
            Contract.Requires(source != null, "You must supply a valid, remote source path to complete this operation.");

            HttpClient client          = this.CreateHttpClient();            
            HttpRequestMessage request = this.CreateRequestMessage(HttpMethod.Head, new Uri(this.Context.ServiceDescription.Url + "/" + source), null);
            HttpResponseMessage msg    = client.SendAsync(request).Result;

            if (this.IsStatusNormal(msg.StatusCode))
            {
                msg.Content.LoadIntoBufferAsync();
                List<KeyValuePair<string, string>> extendedProperties = new List<KeyValuePair<string, string>>();

                foreach (KeyValuePair<string, IEnumerable<string>> header in msg.Headers)
                {
                    if (header.Key.StartsWith("X-"))
                    {
                        extendedProperties.Add(new KeyValuePair<string, string>(header.Key, header.Value.First()));
                    }
                }

                return extendedProperties;
            }
            else
            {
                //throw ExceptionFactory.CreateStorageObjectRepositoryException(msg);
            }
            
            return null;
        }
//======================================================================================================================
/// <summary>
/// 
/// </summary>
//======================================================================================================================
        public void SaveContainer(string name)
        {                     
            Uri uri                = new Uri(this.Context.ServiceDescription.Url + "/" + name);
            HttpRequestMessage msg = this.CreateRequestMessage(HttpMethod.Put, uri, null, null);
            HttpClient client      = this.CreateHttpClient();

            System.Net.Http.HttpResponseMessage response = client.SendAsync(msg).Result;            
        }
//======================================================================================================================
/// <summary>
/// 
/// </summary>
//======================================================================================================================
        public void SaveContainer(StorageContainer storageContainer)
        {
            this.SaveContainer(storageContainer.Name);
        }
//======================================================================================================================
/// <summary>
/// 
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
//======================================================================================================================
        private string GetDNSPortion(string url)
        {
            string[] elements = url.Split('/');
            return elements[2];
        }
//======================================================================================================================
/// <summary>
/// 
/// </summary>
/// <param name="address"></param>
/// <returns></returns>
//======================================================================================================================
        private string GetContainerName(string url)
        {
            string[] elements = url.Split('/');
            return elements[elements.Length - 1];
        }
//======================================================================================================================
/// <summary>
/// 
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
//======================================================================================================================
        private List<StorageContainer> GetSharedContainers(string url)
        {
            List<StorageContainer> results   = new List<StorageContainer>();
            string configFilePath            = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + @"\" + @"HP\CLI.config";
            XDocument doc                    = XDocument.Load(configFilePath);
            IEnumerable<XElement> containers = doc.XPathSelectElements("//SharedContainer");
            
            foreach (XElement element in containers)
            {
                string sharedPath = (string)element.Attribute("url");

                if (this.GetDNSPortion(sharedPath) == this.GetDNSPortion(url))
                {
                    StorageContainer container = new StorageContainer();
                    string containerName = this.GetContainerName(sharedPath);
                    container.SharePath  = sharedPath.Replace("/" + containerName, String.Empty);
                    container.Name       = containerName;
                    results.Add(container);
                }
            }
           
            return results;
        }
//======================================================================================================================
/// <summary>
/// 
/// </summary>
/// <returns></returns>
//======================================================================================================================
        public List<StorageContainer> GetStorageContainers()
        { 
            HttpClient client                        = this.CreateHttpClient();
            List<StorageContainer> storageContainers = new List<StorageContainer>();
            client.DefaultRequestHeaders.Remove("Accept");

            try
            {
                // We're passing the ServiceContext for BlockStorage here from set-zone which is a bug.

                HttpResponseMessage response = client.GetAsync(this.Context.ServiceDescription.Url).Result;
                StreamReader reader          = new StreamReader(response.Content.ReadAsStreamAsync().Result);
                string[] containerNames      = reader.ReadToEnd().Split(System.Environment.NewLine.ToCharArray());

                foreach (string containerName in containerNames)
                {
                    if (containerName == "404 Not Found") return null;

                    storageContainers.Add(new StorageContainer(containerName));
                }
                return storageContainers.Union(this.GetSharedContainers(this.Context.ServiceDescription.Url)).ToList();
            }
            catch (Exception ex)
            { }
            return null;
        }
        #endregion
    }
    }

